<template>
	<div class="container">
    <el-card class="form">
<!--      登录-->
      <el-form-item>
        <h1 style="margin-left: 175px">登录表单</h1>
      </el-form-item>
				<el-form :model="form" autocomplete="off" :rules="rules" ref="formRef">

					<el-form-item class="border" prop="username" :error="errors.username">
						<el-input v-model="form.username" placeholder="用户名" :prefix-icon="User" />
					</el-form-item>

					<el-form-item prop="password" :error="errors.password">
						<el-input v-model="form.password" type="password" placeholder="密码" show-password :prefix-icon="Lock" />
					</el-form-item>

          <el-form-item>
            <el-input :prefix-icon="Lock" style="width: 300px" placeholder="请输入验证码" v-model="sidentifyMode" clearable @keydown.enter="handleSubmit"></el-input>
            <div class="code" @click="refreshCode">
              <Sidentify :identifyCode="identifyCode"></Sidentify>
            </div>
          </el-form-item>

					<el-button id="loginButton" type="primary" @click="handleSubmit" :loading="buttonLoading">登录</el-button>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister=true;clearRegisterData()">
              注册 →
            </el-link>
          </el-form-item>
				</el-form>
<!--      注册表单-->
    </el-card>
	</div>
</template>

<script setup>
import { User, Lock } from '@element-plus/icons-vue';
import {onMounted, reactive, ref} from 'vue';
import { ElMessage } from 'element-plus';
import{ loginUser}from'@/api/getData.js'
import  router  from "../../router";
import Sidentify from "@/views/login/Sidentify.vue";
import {
		setStorage
	} from '@/utils/localStorage.js'

//控制注册与登录表单的显示， 默认显示登录
const isRegister = ref(false)
const formRef = ref(null);
const buttonLoading=ref(false)

const form = reactive({
	username: '',
	password: ''
});

const errors = reactive({
	username: '',
	password: ''
});

//注册
const registerData = reactive({
  userId:'',
  password:'',
  rePassword:'',
  username:'',
  role:'',
})
const clearRegisterData = ()=>{
  registerData.value={
    userId:'',
    password:'',
    rePassword:'',
    username:'',
    role:'',
  }
}
//检验密码函数
const checkRePassword = (rule,value,callback)=>{
  if(value===''){
    callback(new Error('请再次确认密码'))
  }else if(value !== registerData.value.password){
    callback(new Error('请确保两次输入的密码一致'))
  }else{
    callback()
  }
}
const validateUsername = (rule, value, callback) => {
	if (value === '') {
		errors.username = '请输入用户名';
		callback(new Error('请输入用户名'));
	} 
	else {
		errors.username = '';
		callback();
	}
};

const validatePassword = (rule, value, callback) => {
	if (value === '') {
		errors.password = '请输入密码';
		callback(new Error('请输入密码'));
	} else {
		errors.password = '';
		callback();
	}
};

const rules = {
	// username: [{ validator: validateUsername, trigger: 'blur' }],
	// password: [{ validator: validatePassword, trigger: 'blur' }],
  username:[
    {required:true,message:'请输入昵称',trigger:'blur'},
    {min:1,max:20,message:'长度应为1~20位非空字符',trigger:'blur'}
  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {min:1,max:20,message:'长度应为1~20位非空字符',trigger:'blur'}
  ],
  rePassword:[
    {validator:checkRePassword,trigger:'blur'}
  ],
  userId:[
    {required:true,message:'请输入用户名',trigger:'blur'},
    {min:1,max:20,message:'长度应为1~20位非空字符',trigger:'blur'}
  ],
  role:[
    {required:true,message:'请输入身份',trigger:'blur'},
    {min:1,max:20,message:'长度应为1~20位非空字符',trigger:'blur'}
  ]
};

const login = () => {
		buttonLoading.value = true;
		loginUser(form).then(res => {
			if (res !== -1) { //登录功能
				//登录成功提示
				ElMessage.success("登录成功")
        console.log('loginres',res);
				//保存token,用户信息, 用户菜单到浏览器缓存
				setStorage("Token", res.datas.token);
				setStorage("userInfo", JSON.stringify(res.datas));
				//页面跳转
				router.push("/home");

			}
			setTimeout(() => {
				buttonLoading.value = false;
			}, 2000)
			
		})
	}
const handleSubmit = () => {
	formRef.value.validate((valid) => {
		if (valid) {
			login();
			// router.push({ path: "/home" });
			// ElMessage.success('登录成功');
		} else {
			ElMessage.error('请检查表单输入');
			return false;
		}
	});
};

//验证码
let sidentifyMode = ref('') //输入框验证码
let identifyCode = ref('') //图形验证码
let identifyCodes = ref('1234567890abcdefjhijklinopqrsduvwxyz') //验证码出现的数字和字母
onMounted(() => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
})

// 生成随机数
const randomNum = (min, max) => {
  max = max + 1
  return Math.floor(Math.random() * (max - min) + min)
}
// 随机生成验证码字符串
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)]
  }
}
// 更新验证码
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
}
</script>

<style scoped>
.login-main {
	display: flex;
	justify-content: center;
	background-color: rgb(46, 58, 75);
	height: 100vh;
}

.login-title {
	font-size: 30px;
	margin-top: 120px;
	color: white;
	text-align: center;
}

.login-element {
	margin-top: 30px;
	height: 50%;
	background-color: rgb(46, 58, 75);
	width: 250px;
}

#loginButton {
	width: 100%;
}

.border {
	margin-bottom: 20px;
}

.login-info {
	margin-top: 3%;
	color: darkgray;
	font-size: 12px;
}



.container{
  margin: 0;
  min-height: 100vh;
  background-color: #cce5ff;
  background-image:
      radial-gradient(closest-side,rgba(112, 134, 182, 1),rgba(222, 243, 248, 0));
  background-size:
      130vmax 130vmax,
      80vmax 80vmax,
      90vmax 90vmax,
      110vmax 110vmax,
      90vmax 90vmax;
  background-position:
      -80vmax -80vmax,
      60vmax -30vmax,
      10vmax 10vmax,
      -30vmax -10vmax,
      50vmax 50vmax;
  background-repeat: no-repeat;
  animation: 8s movement linear infinite;

  body::after {
    content: '';
    display: block;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
  }

  @keyframes movement {
    0%, 100% {
      background-size:
          130vmax 130vmax,
          80vmax 80vmax,
          90vmax 90vmax,
          110vmax 110vmax,
          90vmax 90vmax;
      background-position:
          -80vmax -80vmax,
          60vmax -30vmax,
          10vmax 10vmax,
          -30vmax -10vmax,
          50vmax 50vmax;
    }
    25% {
      background-size:
          100vmax 100vmax,
          90vmax 90vmax,
          100vmax 100vmax,
          90vmax 90vmax,
          60vmax 60vmax;
      background-position:
          -60vmax -90vmax,
          50vmax -40vmax,
          0vmax -20vmax,
          -40vmax -20vmax,
          40vmax 60vmax;
    }
    50% {
      background-size:
          80vmax 80vmax,
          110vmax 110vmax,
          80vmax 80vmax,
          60vmax 60vmax,
          80vmax 80vmax;
      background-position:
          -50vmax -70vmax,
          40vmax -30vmax,
          10vmax 0vmax,
          20vmax 10vmax,
          30vmax 70vmax;
    }
    75% {
      background-size:
          90vmax 90vmax,
          90vmax 90vmax,
          100vmax 100vmax,
          90vmax 90vmax,
          70vmax 70vmax;
      background-position:
          -50vmax -40vmax,
          50vmax -30vmax,
          20vmax 0vmax,
          -10vmax 10vmax,
          40vmax 60vmax;
    }
  }
}

.form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  user-select: none;
  width: 500px;
  z-index: 1000;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .title {
    margin: 0 auto;
  }
  .button {
    width: 100%;
  }
  .flex {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
.code{
  padding-left: 30px;
  padding-top: 10px;
}
</style>